<!DOCTYPE html>
<title>cruscotto</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<html>

	<link type="text/css" rel="stylesheet" href="css/leaflet.css" />
	<link type="text/css" rel="stylesheet" href="css/bjqs.css" />
	<link type="text/css" rel="stylesheet" href="css/jquery-ui.css" />
	
	<!--[if lte IE 8]>
	<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" />
	<![endif]-->
	<!--
	<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	-->

	<script type="text/javascript" src="js/leaflet.js"></script>
	<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
	<script type="text/javascript" src="js/bjqs-1.3.min.js"></script>
	<script type="text/javascript" src="js/jquery.scrollbox.js"></script>
	<script type="text/javascript" src="js/jquery-ui.js"></script>
	<script type="text/javascript" src="js/jquery.fullscreen-0.3.5.min.js"></script>
	<script type="text/javascript" src="js/jquery.formatDateTime.min.js"></script>
	
	
	<style>
		body {
			padding: 0;
			margin: 0;
		}
		html, body, #map {
			width: 100%;
			height: 100%;
		}
		
		.lastupdate {
			background-color: #0E73B7; /* #FFFFFF;*/
			background-image: url("images/update.png");
			background-position: 5px 5px;
			background-repeat: no-repeat;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4);
			clear: both;
			color: #FFFFFF;
			margin-top: 10px;
			margin-left: 10px;
			padding: 6px 6px 6px 30px;
			z-index: 7;
			opacity: 0.7;
		}

		/* NEWS */
		#newsDiv {
			width: 75%;		
		}
		.news-box {
			overflow: hidden;
			width: 100%;
			height: 80px;
			background-color: rgba(14,115,183,0.8);
			border-radius: 8px;
			margin-bottom: 15px;
			margin-left: 10px; 
			display: inline-block;
			padding: 8px 8px 8px 8px;
		}
		.news {
			overflow: hidden;
			background-color: #0E73B7;
			width: 100%;
			height: 100%;
			margin-right: 10px;
			font: 24px Arial, Helvetica, sans-serif;
			background-image: url("images/piacenza_comune.png");
			background-position: 15px 10px;
			background-repeat: no-repeat;
			background-size : 35px 60px;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4);
			clear: both;
			color: #FFFFFF; /*#333333;*/
/* 			padding: 5px 5px 5px 70px; */
			z-index: 8;
			opacity: 0.9;
		}
		.news li {
			/* TODO allineare meglio testo verticalmente */
			vertical-align:middle; /* MOD */
			padding: 25px 5px 5px 70px; /* MOD */
			width: 100%;
		}
		
		/* EVENTI / ALERT */
		#eventsDiv {
			height: 100%;
			width: 22%;
			min-width: 300px;
		}
		.events-box {
			height: 94%; 
/* 			width: 270px; */
			overflow: hidden;
			background-color: rgba(14,115,183,0.8);
			/* TODO stemma custom */
			background-image: url("images/piacenza_comune.png");
			background-repeat: no-repeat;
			background-position: 10px 10px;
			background-size : 35px 60px;
			margin-top: 2%;
			margin-bottom: 2%;
			margin-right: 5px;
			margin-left: 5px;
			color: #FFFFFF;
			border-radius: 8px;
			padding: 10px 10px 10px 10px;
			z-index: 10;
		}
		.events-title {
			height: 10%;
			font: 1.8em Arial, Helvetica, sans-serif;
			font-weight: bold;
			margin-left: 20px;
			text-align: center;
		}
		.events-title span {
			display:block;
			font: 0.7em Arial, Helvetica, sans-serif;
			margin-left: auto;
			margin-right: auto;
			margin-top:0.4em;
			width: 8em;
			padding: 3px;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(255, 255, 255, 0.4);
		}
		.events {
			overflow: hidden;
			height: 88%;
			padding: 10px 10px 10px 10px;
			opacity: 0.8;
			font: 14px Arial, Helvetica, sans-serif;
			background-color: #0E73B7;
			color: #FFFFFF;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.9);
			padding: 6px 6px 6px 6px;
			z-index: 11;
		}
		.events ul {
			overflow: hidden;
			list-style-type: none;
/* 			height: 100%; */
/*   		padding-top: 5px; padding-bottom: 5px; */
			font-size: 0;
			margin:0px 10px 0px 10px;
   			padding:0;
		}
		.events li {
			overflow: hidden;
			margin-top: 10px;
			width: 100%;
			height:100%;
			font-size: 14px;
			border-bottom: 2px solid rgba(255,255,255,0.6); 
		}
		.title{
			font-weight: bold;
			font-size: 1.2em;
		}
		.icon{
			width: 25px;
			height: 25px;	
			margin-left:5px;
		}
		.icon-alert{
			width: 22px;
			height: 32px;	
			margin: 0;
			vertical-align: middle;
		}
		
		/* SETUP */
		
		/*
		.leaflet-bar a {
			opacity : 0.8;
			background-color: rgba(14,115,183,0.8);
		}
		.leaflet-bar a:hover {
			opacity : 1;
		}
		*/
		
		.setup img{
			margin-top:2px;
			background-color: transparent;
			opacity : 0.7;
		}		
		#dialog-form{
			display: none;
		}
		.dialog-form{
			overflow-y:scroll ;
			width: 100%;
		}
		.dialog-form .stemma{
			position:absolute;
			height:auto;
			left:560px;
			top: 30px;
		}
		.dialog-form label{
			display: inline-block;
			/*min-width: 100px;*/
			overflow: hidden;
		}
		.dialog-form input{
			float:right;
			width: 100%;
		}
		.dialog-form input.field-n{
			float:none;
			width: 150px;
		}
		.dialog-form input.field-t{
			float:none;
			width: 306px;
		}
		.dialog-form td{
			margin: 0;
			padding: 2px;
		}
		.table-news{
			width: 100%;
		}
		.table-news input{
			width: 90%;
		}
		
	</style>

	<body>
		<?php
			date_default_timezone_set('Europe/Rome');
			//$key = $_GET["key"];
			$code = $_GET["code"];
		?>
		<!--
		<pre>
			code:<?php echo $code ?>
		</pre>
		-->
		<div id="map">
			<div id="newsDiv" class="leaflet-bottom">
				<div class="news-box" >
					<div class="news" id="banner-news">
						<ul class="bjqs">						
							<li>
								File news non trovato
							</li>						
						</ul>
					</div>
				</div>
			</div>
			<div id="eventsDiv" class="leaflet-top leaflet-right">
				<div class="events-box" id="box" >
					<div class="events-title">
						<div id="titolo" >Comune di Piacenza</div><span id="time">00:00</span>
					</div>
					<div id="events" class="events" >
						<ul><!--
							<li><span><img width="40px" src="images/RCA.png" /></span>
								Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet lorem in lacus semper pretium. Quisque vitae lacinia sapien, nec convallis velit. Donec quis orci at ipsum sodales commodo vitae at augue. Morbi iaculis adipiscing arcu, pharetra rutrum metus iaculis sit amet. In imperdiet, urna non rutrum interdum, urna erat euismod urna, nec condimentum justo lorem vel magna. Sed sed pretium lectus, quis pharetra elit. Phasellus egestas sapien sed arcu iaculis, pellentesque commodo nunc suscipit.
							</li>
							<li><span><img width="40px" src="images/RWK.png" /></span>
								Vestibulum interdum augue quis sollicitudin mollis. Sed sit amet dui arcu. Vestibulum mollis condimentum justo blandit elementum. Aenean nec elementum libero. Aliquam diam nisl, vehicula accumsan auctor a, volutpat vehicula nisl. Duis at luctus mauris. Maecenas venenatis diam congue vehicula hendrerit. Nunc interdum lacus eu semper sagittis. Sed mattis quam id tortor lacinia hendrerit. Morbi blandit dapibus nulla a elementum.
							</li>
							<li><span><img width="40px" src="images/WIG.png" /></span>
								Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla facilisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum malesuada vestibulum tellus, et lobortis massa aliquet eu. Suspendisse tempor molestie rhoncus. Vivamus tempus dolor id diam accumsan aliquam. Praesent sollicitudin dolor tellus, tempus laoreet risus venenatis adipiscing. Maecenas hendrerit, odio nec mollis gravida, lorem risus aliquet augue, id varius justo leo ut mi. Ut pellentesque molestie accumsan.
							</li>
							<li><span><img width="40px" src="images/RCA.png" /></span>
								Aliquam nec metus at libero cursus vestibulum. Cras dui ante, congue vel nisi non, vulputate sodales neque. Nunc pulvinar erat sed ipsum ornare elementum. Donec vulputate erat ante, posuere sagittis felis euismod tristique. Integer ultrices neque mauris, a blandit lectus condimentum at. Vivamus laoreet felis et nunc dictum volutpat. Vivamus bibendum ac ante eu egestas.
							</li>
							<li></li>
							-->
							<li></li>
							<li></li>
						</ul>
					</div>
				</div>
			</div>
		</div>
		
		<div id="dialog-form" class="dialog-form" title="Configurazione Cruscotto" >
			<form>
				<fieldset>
					<span class="stemma"><img id="stemma-img" width="60px"/></span>
				<table style="overflow-y:scroll ; width: 100%;">
					<tr><td>
						<label for="codice">Codice Catastale</label>
					</td><td>
						<input type="text" name="codice" id="codice" value="" class="field-n text ui-widget-content ui-corner-all">
						<button id="cerca">Cerca</button>
					</td></tr>
					<tr><td style="width: 200px">
						<label for="name">Comune</label>
					</td><td style="width: 600px">
						<input type="text" name="comune" id="comune" class="field-t text ui-widget-content ui-corner-all">
					</td></tr>
					<tr><td style="width: 200px">
						<label for="name">Stemma</label>
					</td><td style="width: 600px">
						<input type="file" name="stemma" id="stemma" class="field-t text ui-widget-content ui-corner-all">
					</td></tr>
					<!--
					<tr><td>
						<label for="chiave">Chiave Attivazione</label>
					</td><td>
						<input type="text" name="chiave" id="chiave" value="" class="field-t text ui-widget-content ui-corner-all">
					</td></tr>
					-->
					<tr>
						<td><label for="coordinate">Coordinate</label>
					</td><td>
						<input type="text" readonly name="lat" id="lat" value="" class="field-n">
						<input type="text" readonly name="lng" id="lng" value="" class="field-n">
					</td></tr>
					<tr><td>
						<label for="zoom">Zoom</label>
					</td><td>
						<input type="text" readonly name="zoom" id="zoom" value="" class="field-n">
					</td></tr>
					<tr><td colspan="2">
						<table>
							<tr >
								<td><b>Elenco News</b>&nbsp;<button id="nuova">Nuova</button></td>
							</tr>
						</table>
						<table id="table-news" class="table-news" >
							<tr></tr>
							<!-- 
							<tr >
								<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-1" value="Sottopassaggio via Calindri allagato " ></td>
							</tr>
							<tr>
								<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-2" value="Domenica blocco del traffico dalle 9 alle 17"></td>
							</tr>
							<tr>
								<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-3" value="Viale certosa chiuso per traffico"  ></td>
							</tr>
							<tr>
								<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-4"  value="Parata musicale in corso Garibaldi il 27/5/2013"  ></td>
							</tr>
							 -->
							 
						</table>
					</td></tr>
						
				</table>
				
				</fieldset>
				
			</form>
		</div>
		
		<script>

			/*
			function getColor(d) {
				return d > 1000 ? '#800026' : d > 500 ? '#BD0026' : d > 200 ? '#E31A1C' : d > 100 ? '#FC4E2A' : d > 50 ? '#FD8D3C' : d > 20 ? '#FEB24C' : d > 10 ? '#FED976' : '#FFEDA0';
			}
			*/

			function loadLayer(url, z_index) {
				var attribution = "Traffic data &copy QMap s.r.l., Map data &copy OpenStreetMap contributors";
				z_index = typeof z_index !== 'undefined' ? z_index : 1;
				//alert(z_index);
				var layer = new L.TileLayer(url, {
					minZoom : 6,
					maxZoom : 16,
					attribution : attribution,
					zIndex : z_index,
					timestamp : releaseId //new Date().getTime()
				});
				return layer;
			}

			function refreshLastUpdate() {
				var url = api_server_url + '/api/lastupdate';
				$.ajax({
					url : url,
					dataType : 'jsonp',
					success : function(json) {
						//updateTimeDiv.html("<div class='lastupdate'>Ultimo aggiornamento: " + json.lastUpdate.substring(0, json.lastUpdate.length - 3) + "</div>");
						updateTraffic(json.releaseId);
						releaseId = json.releaseId;
					},
					error : function(jqXHR, textStatus, errorThrown) {
						updateTimeDiv.html("Errore update");
					}
				});
			}

			function updateTraffic(release) {
				 if (releaseId < release) {
					 trafficLayer.options.timestamp = releaseId;
					 trafficLayer.redraw();
				}
			}
			
			function refreshEvents() {
				//console.error("refreshEvents");
				$("#events ul").empty();
				loadAlerts();
				loadEvents();
				// clock 
				try {
				  var now = new Date("<?php echo date('D M d Y H:i:s O'); ?>");
				  var str = $.formatDateTime('hh:ii d/m/yy',now);
				  //alert(str);
				  $("#time").text(str);
				}
				catch(err) { 
				  console.error(err);
				}
			}
			
			function loadEvents() {
				if (enable_event) {
					
					var zoom = map.getZoom();

					var eventsIconUrl = '';

					var geojsonEventOptions = {
						pointToLayer : function(feature, latlng) {

							/*
							var lcdFrom = feature.properties.lcd_from;
							var lcdTo = feature.properties.lcd_to;
							var roaLcd = feature.properties.roa_lcd;
							var ogc_fid = feature.properties.ogc_fid;
							var dir = feature.properties.dir;
							*/
							
							var eventTypeId = feature.properties.event_type_id;

							eventsIconUrl = api_server_url + '/api/eventicons/' + eventTypeId;

							var pointMarker = L.marker(latlng, {
								icon : L.icon({
									iconUrl : eventsIconUrl,
									iconSize : [25, 25],
									iconAnchor : [13, 25],
									popupAnchor : [0, -25]
								})
							});
							
							/*
							pointMarker.bindPopup(LOADING_STRING, options = {
								maxWidth : 500,
								autoPan : false
							});
							*/
//							var url = api_server_url + '/api/event/' + ogc_fid + '/' + roaLcd + '/' + dir + '/' + lcdFrom + '/' + lcdTo;
							
// 							pointMarker.on('click', function(e) {
// 								//console.error(url);
// 								//alert(url);
// 								$.ajax({
// 									url : url,
// 									dataType : 'html',
// 									type : 'GET',
// 									success : function(output) {
// 										$(".leaflet-popup-content").html(output);
// 									},
// 									error : function(jqXHR, textStatus, errorThrown) {
// 										console.error("ERROR:" + jqXHR);
// 										$(".leaflet-popup-content").html("Errore nel caricamento dati dal server: " + errorThrown);
// 									}
// 								});
// 							});

							return pointMarker;
						}
					};

					if (zoom >= 6) {// in pratica sempre 
						/**
						 * @type LatLngBounds
						 */
						var bounds = map.getBounds();

						var url = api_server_url + '/api/events/' + zoom + '/' + bounds.toBBoxString();

						$.ajax({
							url : url,
							dataType : 'jsonp',
							success : function(data) {
						
								eventsLayer.clearLayers();
								eventsLayer = L.geoJson(data, geojsonEventOptions);
				
								map.addLayer(eventsLayer);
														
								// carica eventi	
								
								//console.error("EVENT LEN:"+data.features.length);						
								//var list = $("#events ul");
								// clear list per refresh
								//list.empty();
		                        $.each(data.features, function(i) {
		                        	//console.error("dettaglio "+i);
		                        	var e = data.features[i];								
								    var durl = api_server_url+"/api/event/"+e.properties.ogc_fid+"/"+e.properties.lcd_from+"/"+e.properties.lcd_to+"/"+e.properties.roa_lcd+"/"+e.properties.dir+".json";
								    dettaglioEvento(durl);							    
								});                    
							},
							error : function(jqXHR, textStatus, errorThrown) {
								eventsLayer.clearLayers();
							}
						});
					} else {
						eventsLayer.clearLayers();
					}
					
				}

			}

			function dettaglioEvento(url){
	                $.ajax({
	                    url : url,
	                    dataType : 'jsonp',
	                    type : 'GET',
	                    success : function(data) {
	                    	var list = $("#events ul");
	                    	var li = $('<li/>').appendTo(list);
	                    	var icon1 = "<img class='icon' src='"+api_server_url+"/api/eventicons/"+data.event_type_id+"' />" ;
	                    	var icon2 = data.cause_id!=""?"<img class='icon' src='"+api_server_url+"/api/eventicons/"+data.cause_id+"' />":"" ;
	                    	li.append("<p class='title'>"+data.event_name+"</p><span>"+icon1+icon2+"</span>"
	                    		+"<p>"+data.further_info+"</p>");
	                        //li.append("<p>"+JSON.stringify(data)+"</p>");
	                    },
	                    error : function(jqXHR, textStatus, errorThrown) {
	                        console.error("Errore nel caricamento dati dal server: " + errorThrown);
	                    }
	                });
            }

			/**
			 * Carica gli Alerts attraverso richesta ajax JSON/JSONP
			 * 
			 * @returns {undefined}
			 */
			function loadAlerts() {
			    if (enable_alert) {
			        var zoom = map.getZoom();

			        var alertIconUrl_1 = 'images/alert1.png';
			        var alertIconUrl_2 = 'images/alert2.png';
			        var alertIconUrl_3 = 'images/alert3.png';

			        var geojsonAlertOptions = {
			            pointToLayer: function(feature, latlng) {
				            
			                var levelId = feature.properties.level_id;
			                /*
			                var lcdFrom = feature.properties.lcd_from;
			                var lcdTo = feature.properties.lcd_to;
			                var roaLcd = feature.properties.roa_lcd;
			                var roadDir = feature.properties.road_dir;
							*/
			                var iconUrl = '';

			                if (levelId == 1) {
			                    iconUrl = alertIconUrl_1;
			                } else if (levelId == 2) {
			                    iconUrl = alertIconUrl_2;
			                } else if (levelId == 3) {
			                    iconUrl = alertIconUrl_3;
			                }

			                var pointMarker = L.marker(latlng, {
			                    icon: L.icon({
			                        iconUrl: iconUrl,
			                        iconSize: [25, 41],
			                        iconAnchor: [13, 41],
			                        popupAnchor: [0, -41]
			                    })
			                });
			                /*
			                pointMarker.bindPopup(LOADING_STRING, options = {
			                    maxWidth: 500,
			                    autoPan: false
			                });
							*/
//			                var url = api_server_url + '/api/anomaly/' + lcdFrom + '/'+ lcdTo + '/' + roaLcd + '/' + roadDir;
// 			                pointMarker.on('click', function(e) {
// 			                    $.ajax({
// 			                        url: url,
// 			                        dataType: 'html',
// 			                        success: function(html) {
// 			                            $(".leaflet-popup-content").html(html);
// 			                        },
// 			                        error: function(jqXHR, textStatus, errorThrown) {
// 			                            $(".leaflet-popup-content").html(
// 			                                    "Errore nel caricamento dati dal server: "
// 			                                    + errorThrown);
// 			                        }
// 			                    });

// 			                });

			                return pointMarker;
			            }
			        };

			        if (zoom >= 6) { // in pratica sempre
			            /**
			             * @type LatLngBounds
			             */
			            var bounds = map.getBounds();

			            var url = api_server_url + '/api/alerts/' + zoom + '/'+ bounds.toBBoxString();
			            $.ajax({
			                url: url,
			                dataType: 'jsonp',
			                success: function(data) {
			                    alertsLayer.clearLayers();
			                    // alertsLayer = L.geoJson(features, geojsonAlertOptions)
			                    // .addTo(map);
			                    alertsLayer = L.geoJson(data.features, geojsonAlertOptions);
// 			                    alertsMarkerGroup.clearLayers();
// 			                    alertsMarkerGroup.addLayer(alertsLayer);		
								map.addLayer(alertsLayer);
								// carica alerts 
								//console.error("ALERT LEN:"+data.features.length);			
								//var list = $("#events ul");
								// clear list per refresh
								//list.empty();
		                        $.each(data.features, function(i) {
		                        	//console.error("dettaglio "+i);
		                        	var e = data.features[i];								
								    //var durl = api_server_url+"/api/alerts/"+e.properties.ogc_fid+"/"+e.properties.lcd_from+"/"+e.properties.lcd_to+"/"+e.properties.roa_lcd+"/"+e.properties.dir+".json";
								    var durl = api_server_url+"/api/anomaly/"+e.properties.lcd_from+"/"+e.properties.lcd_to+"/"+e.properties.roa_lcd+"/"+e.properties.road_dir+".json";
									var level = +e.properties.level_id;
								    dettaglioAlert(durl,level);							    
								});		
			                },
			                error: function(jqXHR, textStatus, errorThrown) {
			                    alertsLayer.clearLayers();
			                }
			            })
			        } else {
			            alertsLayer.clearLayers();
			        }
// 			        map.addLayer(alertsMarkerGroup);

			    }
			}
				
		 	function dettaglioAlert(url,level){
		 		//console.error("ALERT:"+url);
	                $.ajax({
	                    url : url,
	                    dataType : 'jsonp',
	                    type : 'GET',
	                    success : function(data) {
	                    	var list = $("#events ul");
	                    	var li = $('<li/>').appendTo(list);
	                    	// TODO 
	                    	var icon = "<img class='icon-alert' src='images/alert"+level+".png' />" ;
	                    	var titolo =data.std_roadnumber + " "+ data.std_roadname;
	                    	var info = "<b>Inizio: </b>"+data.name_from+"<br><b>Fine: </b>"+data.name_to+"</br><b>"+data.std_road_direction_name+"</b><br>"
	                    		+"<b>Rilevamento: </b>"+data.get_segment_last_speeds+"<br><b>Data: </b>"+data.start_date;
// 	                    	var icon2 = data.cause_id!=""?"<img class='icon' src='"+api_server_url+"/api/eventicons/"+data.cause_id+"' />":"" ;
 	                    	li.append("<p class='title'>"+titolo+"</p><span>"+icon+"</span>"+"<p>"+info+"</p>");
//							+"<p>"+data.further_info+"</p>");
//	                        li.append("<p>"+JSON.stringify(data)+"</p>");
	                    },
	                    error : function(jqXHR, textStatus, errorThrown) {
	                        console.error("Errore nel caricamento dati dal server: " + errorThrown);
	                    }
	                });
            }
			
			function loadNews(){
			   $.get('data/<?php echo $code.".txt"?>', function(data) {
				   //alert(data);
				   //process text file line by line
				   $('#banner-news ul').empty();
				   $('#table-news').empty();
				   var lines = data.split("\n");
				   //alert(lines);
				   for (var i = 0, len = lines.length; i < len; i++) {
	            		if(lines[i]!=''){
	            			$('#banner-news ul').append("<li>"+lines[i]+"</li>");
	            			$('#table-news').append("<tr id='row-"+i+"'><td><button class='btn-del' id='btn-"+i+
	    				    		"'>X</button><input class='ui-widget-content ui-corner-all' type='text' name='n-"+i+"' value='"+lines[i]+"'  ></td></tr>");
		            	}
	            		refreshButtons();
	        		}
				   //$('#news').html(data.replace('\n','<br>'));
				}).fail(function() {
				    alert( "errore lettura file news" );
				}).always(function() {
				    $('#banner-news').bjqs({
				    	height : '100%',
						width : '100%',
						responsive : false,
						animspeed : 6000,
						showmarkers : false,
						showcontrols : false
					});
				});
			}

			var SetupCruscotto = L.Control.extend({
			    options: {
			        position: 'topleft'
			    },
			    onAdd: function (map) {
			        // create the control container with a particular class name
			        var container = L.DomUtil.create('div', ' leaflet-bar');
			        this._map = map;

					this._setupButton  = this._createButton(
					        "<img  src='images/gear-mini.png' />", 
					        'Setup',  'setup',  container, this._setup,  this);
	
					//map.on('zoomend zoomlevelschange', this._updateDisabled, this);

			        return container;
			   },
			   _setup: function (e) {
					$('#zoom').val(map.getZoom());
					$('#lat').val(map.getCenter().lat.toFixed(8));
					$('#lng').val(map.getCenter().lng.toFixed(8));
					$( "#dialog-form" ).dialog( "open" );
				},
			  _createButton: function (html, title, className, container, fn, context) {
					var link = L.DomUtil.create('a', className, container);
					link.innerHTML = html;
					link.href = '#';
					link.title = title;
			
					var stop = L.DomEvent.stopPropagation;
			
					L.DomEvent
					    .on(link, 'click', stop)
					    .on(link, 'mousedown', stop)
					    .on(link, 'dblclick', stop)
					    .on(link, 'click', L.DomEvent.preventDefault)
					    .on(link, 'click', fn, context);
			
					return link;
				},
			});
			
			function setupDialog(){
				 $( "#dialog-form" ).dialog({
					autoOpen: false,
					height: 500,
					width: 700,
					modal: true,
					buttons: {
						"Refresh Map": function() {
							refreshLastUpdate();
							refreshEvents();
							$('body').fullscreen();
							$( this ).dialog( "close" );
						},	
						"Carica News": function() {
							// CARICA
							$('#banner-news ul').empty();
							$.each($('#table-news tr input'), function( index, elem ) {
								var value = $(elem).val();
								//alert( index + ": " + value );
								$('#banner-news ul').append("<li>"+value+"</li>");
								$('#banner-news').bjqs({
							    	height : '100%',
									width : '100%',
									responsive : false,
									animspeed : 6000,
									showmarkers : false,
									showcontrols : false
								});
							});
							// MEMORIZZA FORM 
							$('body').fullscreen();
							$( this ).dialog( "close" );
						},
						"Salva": function() {
							var codice = $("#codice").val();
							if(codice=='') alert("Attenzione \n codice catastale \ non impostato !");
							else{
								// UPLOAD 
								$( this ).dialog( "close" );	
							}	
						},
						Cancel: function() {
							// RIPRISTINA FORM
							$( this ).dialog( "close" );
						}
						},
						close: function() {
							//
						}
					});
					$("#stemma").change(function(){
				        readImage(this, $('#stemma-img'));
				    });
				    $("#nuova").click(function(event){
				    	event.preventDefault();
				    	var nr = $('#table-news tr').length;
				    	$('#table-news tr:first').before("<tr id='row-"+(nr+1)+"'><td><button class='btn-del' id='btn-"+(nr+1)+
				    		"'>X</button><input class='ui-widget-content ui-corner-all' type='text' name='n-"+(nr+1)+"' value=''  ></td></tr>");
				    	refreshButtons();
				    });
				    $("#cerca").click(function(event){
				    	event.preventDefault();
				    	var codice = $("#codice").val();
						if(codice=='') alert("Attenzione \n codice catastale \ non impostato !");
						else{
							//
						}
				    });
				    //refreshButtons();
			}
			
			function refreshButtons() {
				// refresh bottoni del news
				$(".btn-del").click(function(event){
				    event.preventDefault();
				    //alert("del");
				    var row = $(this).closest('tr');
				    row.remove();
				});
			}
			
			function readImage(input, img) {
		        if (input.files && input.files[0]) {
		            var reader = new FileReader();	            
		            reader.onload = function (e) {
		            	var id = img.attr('id');
		                $('#'+id).attr('src', e.target.result);
		            };	            
		            reader.readAsDataURL(input.files[0]);
		        }
		    }
			
			var map = L.map('map', {
				zoomControl:false,
				//center : [45.5411870, 10.2194440], // BS
				center: [45.050354,9.6990967] , // PC
				zoom : 11
			});

			//var LOADING_STRING = "<br/><br/><br/><br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Loading...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/><br/><br/><br/><br/>";
			
			var releaseId =0;
			
// 			var updateTimeDiv;
// 			updateTimeDiv = $('.leaflet-top.leaflet-left');

			// BS [45.5411870, 10.2194440]
			// PC [45.05035400390626,9.6990966796875]
			// key leaflet    BC9A493B41014CAABB98F0471D759707
			// key personal   0FBA3CCBEEB240B8B396A762A558E0BB // UPPERCASE e c'è voluto circa 24h per averla attiva 
			// 997 day
			// 999 night

			var api_server_url = "http://osm.qmap.it";
			var tile_server_url = "http://osm.qmap.it";

			//var mapUrl = tile_server_url + "/osm_tiles/{z}/{x}/{y}.png";
			var mapUrl = "http://{s}.tile.cloudmade.com/0FBA3CCBEEB240B8B396A762A558E0BB/999/256/{z}/{x}/{y}.png";
			//var speedUrl = tile_server_url + "/qmap_speed/{z}/{x}/{y}.png?ts={timestamp}";
			var trafficUrl = tile_server_url + "/qmap_traffic/{z}/{x}/{y}.png?ts={timestamp}";
			var mapLayer = loadLayer(mapUrl);
			//var speedLayer = loadLayer(speedUrl, 10);
			var trafficLayer = loadLayer(trafficUrl, 10);
			var eventsLayer = L.geoJson();
			var alertsLayer = L.geoJson();
			
			var enable_event = true;
			var enable_alert = true;
						
			$(document).ready(function() {
				
				map.addLayer(mapLayer);
				//map.addLayer(speedLayer);
				map.addLayer(trafficLayer);
				//refreshLastUpdate();
				// CLEAR EVENT LIST 
				/*
				$("#events ul").empty();
				loadAlerts();
				loadEvents();			
				*/
				refreshEvents();
				loadNews();
				map.addControl(new SetupCruscotto());
				setupDialog();
// 				window.resizeTo(800, 300);
// 				alert($(window).width()+" x "+$(window).height());
				setInterval(refreshEvents,120000); // 2 min 

				$('#events').scrollbox({
					  linear: true,
					  step: 1,
					  delay: 0,
					  speed: 50,
					  onMouseOverPause:false
				});
				
			});

			//alert("EVENTI \n"+ "http://osm.qmap.it/api/events/"+map.getZoom() +"/"+ map.getBounds().toBBoxString());
			//alert("ALLERTE \n"+ "http://osm.qmap.it/api/alerts/"+map.getZoom() +"/"+ map.getBounds().toBBoxString());
			
		</script>

	</body>

</html>
